package cn.tedu.ivos.dict.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.dto.SaveDictDTO;
import cn.tedu.ivos.dict.pojo.entity.Dict;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dict.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author liyuehui
 * @time 2024/7/12 16:09
 */
@Service
public class DictServiveImpl implements DictService {
    @Autowired
    private DictMapper dictMapper;

    /**
     * 查询字典列表
     *
     * @param dictQuery
     * @return
     */
    @Override
    public List<DictVO> select(DictQuery dictQuery) {
        return dictMapper.select(dictQuery);
    }

    /**
     * 保存字典信息
     *
     * @param saveDictDTO
     * @return
     */
    @Override
    public int save(SaveDictDTO saveDictDTO) {
        Dict dict = new Dict();
        BeanUtils.copyProperties(saveDictDTO, dict);
        if (dict.getName() == null){
            throw new ServiceException(StatusCode.DICT_NAME_IS_EMPTY);
        }
        if (dict.getCode() == null){
            throw new ServiceException(StatusCode.DICT_CODE_IS_EMPTY);
        }
        // 判断id是否为空, 如果为空,则新增
        if (dict.getId() == null) {
            //新增
            dict.setCreateTime(new Date());
            //先查询编码是否重复
            DictQuery dictQuery = new DictQuery();
            dictQuery.setCode(dict.getCode());
            if (dictMapper.select(dictQuery).size() > 0) {
                throw new ServiceException(StatusCode.DICT_CODE_ALREADY_EXISTS);
            }
            int result = dictMapper.insert(dict);
            if (result != 1) {
                throw new ServiceException(StatusCode.OPERATION_FAILED);
            }
            return result;
        } else {
            //修改
            dict.setUpdateTime(new Date());
            int result = dictMapper.update(dict);
            if (result != 1) {
                throw new ServiceException(StatusCode.OPERATION_FAILED);
            }
            return result;
        }
    }

    /**
     * 删除字典信息
     *
     * @param dictId
     * @return
     */
    @Override
    public int delete(Long dictId) {
        int result = dictMapper.delete(dictId);
        if (result != 1) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
        return result;
    }
}
